<template>
  <div class="container">
    <!--    depts.length===0-->
    <my-loading v-if="depts.length===0" />
    <div v-else class="app-container">
      <div class="left">
        <el-input
          v-model="pageParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          default-expand-all
          :data="depts"
          :props="defaultProps "
          :highlight-current="true"
          :expand-on-click-node="false"
          @current-change="handleNodeClick"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <!--   添加员工   -->
          <add-employee-button v-permission="'add-employee'" @click.native="$router.push('/employee/detail')" />
          <!--   excel导入员工        -->
          <excel-operation :title="importName" @click.native="showExcelDialog=true" />
          <!--   excel导出员工        -->
          <excel-operation :title="exportName" @click.native="exportEmployee" />
        </el-row>
        <!-- 表格组件 -->
        <!--        employee.length===0 && !timeout-->
        <my-loading v-if="employee.length===0 && !timeout" />
        <el-table v-else :data="employee" stripe border>
          <el-table-column width="100px" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="40" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column align="center " width="140px" prop="mobile" label="手机号" sortable>
            <template v-slot="{ row }">
              <span>{{ row.mobile }}</span>
              <el-tooltip class="item" effect="dark" content="点击复制" placement="top">
                <i style="cursor: pointer;padding-left: 10px" class="el-icon-document-copy" @click="copyText(row.mobile)" />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable>
            <template v-slot="{ row }">
              <el-tooltip class="item" effect="dark" content="点击复制" placement="top">
                <el-tag style="cursor: pointer" @click="copyText(row.workNumber)">{{ row.workNumber }}</el-tag>>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column width="120px" align="center" prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <el-button v-if="row.formOfEmployment===1" type="success" round>正式</el-button>
              <el-button v-else type="info" round>非正式</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column align="center" label="操作" width="180px">
            <template v-slot="{ row }">
              <!--     查看    -->
              <el-button icon="el-icon-search" circle @click="$router.push(`/employee/detail/${row.id}`)" />
              <!--     角色    -->
              <el-button
                type="primary"
                icon="el-icon-user"
                circle
                @click="btnRole(row.id)"
              />
              <!--     删除    -->
              <el-popconfirm
                title="确认删除该行数据吗？"
                style="margin-left: 10px"
                @onConfirm="delEmployee(row.id)"
              >
                <el-button slot="reference" type="danger" icon="el-icon-delete" circle />
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" align="middle" style="height: 60px;" justify="end">
          <span>共 <span style="color: cornflowerblue">{{ pageParams.total }}</span> 条 </span>
          <el-pagination
            :page-size="pageParams.pagesize"
            layout="prev, pager, next"
            :total="pageParams.total"
            :current-page="pageParams.page"
            background
            @current-change="changePage"
          >
            <!--        放置页码 -->
          </el-pagination>
        </el-row>
      </div>
    </div>
    <!--    放置导入excel的弹窗   -->
    <import-excel
      :show-excel-dialog.sync="showExcelDialog"
      @uploadSuccess="getEmployee"
    />
    <!--  分配角色  -->
    <el-dialog
      title="分配角色"
      :visible.sync="showRoleDialog"
      :close-on-click-modal="false"
      width="50%"
    >
      <!--    弹层内容-->
      <my-loading v-if="roleLoading" />
      <template v-else>
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="mini" type="primary" @click="btnRoleOK">确定</el-button>
            <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { transListToTree } from '@/utils'
import {
  getEmployee,
  exportEmployee,
  deleteEmployee,
  getEnabledEmployeeList, getEmployeeDetail, assignRoles
} from '@/api/employee'
import AddEmployeeButton from '@/views/employee/components/add-employee-button.vue'
import ExcelOperation from '@/views/employee/components/excel-operation.vue'
import FileSaver from 'file-saver'
import ImportExcel from '@/views/employee/components/import-excel.vue'

export default {
  name: 'Employee',
  components: { ImportExcel, ExcelOperation, AddEmployeeButton },
  data() {
    return {
      // 导入excel的弹窗
      showExcelDialog: false,
      showRoleDialog: false,
      importName: 'excel导入',
      exportName: 'excel导出',
      depts: [], // 组织数据
      allDepartment: [],
      defaultProps: {
        label: 'name', // 显示的字段的名字
        children: 'children' // 读取子节点的字段名
      },
      queryParams: {
        departmentId: null
      },
      employee: [],
      timeout: false,
      // 查询的参数
      pageParams: {
        page: 1, // 第几页
        pagesize: 10, // 每页多少条
        total: 0,
        keyword: '', // 根据名字模糊查询
        departmentId: '' // 部门id,根据部门查询当前部门及子部门的用户
      },
      // 接收角色列表
      roleList: [],
      // 选中的角色
      roleIds: [],
      // 当前选中的用户id
      curUser: null,
      roleLoading: false
    }
  },
  watch: {
    'pageParams.keyword': {
      handler() {
        this.getEmployee()
      }
    }
  },
  created() {
    this.getDepartment()
    this.getEmployee()
  },
  methods: {
    assignRoles,
    // 获取组织数据并转换为树形结构
    async getDepartment() {
      this.allDepartment = await getDepartment() // 导入的api
      this.depts = transListToTree(this.allDepartment, 0)
      // 选择第一个部门
      this.queryParams.departmentId = this.depts[0].id
      // 树组件的渲染为异步的 等待更新完毕后再更新
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
    },
    // 节点改变
    handleNodeClick(node) {
      this.queryParams.departmentId = node.id
      this.getEmployee()
    },
    // 获取员工数据
    async getEmployee() {
      this.employee = []
      this.timeout = false
      setTimeout(() => {
        this.timeout = true
      }, 3 * 1000)
      const res = await getEmployee({ ...this.pageParams, departmentId: this.queryParams.departmentId })
      this.pageParams.total = res.total
      this.employee = res.rows
    },
    // 分页
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getEmployee()
    },
    // 复制到粘贴板
    copyText(text) {
      navigator.clipboard.writeText(text).then(() => {
        this.$message.success('复制成功')
      })
    },
    // 导出员工信息
    exportEmployee() {
      console.log('导出')
      this.$confirm('是否确认导出员工excel表?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(async() => {
        this.$notify({
          title: '正在导出',
          message: '需要大概30秒',
          type: 'success',
          duration: 0
        })
        // 导出员工excel表
        const res = await exportEmployee()
        // FileSaver.saveAs(blob对象, 文件名.文件类型)
        FileSaver.saveAs(res, '员工信息.xlsx')
        this.$nextTick(() => {
          this.$notify.closeAll()
          this.$notify({
            title: '导出成功',
            message: '已导出请在浏览器下载文件里面查看',
            type: 'success'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出'
        })
      })
    },
    async delEmployee(id) {
      // console.log(id)
      await deleteEmployee(id)
      this.$notify({
        title: '删除成功',
        message: '正在刷新页面',
        type: 'success'
      })
      if (this.employee.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page--
      }
      this.getEmployee()
    },
    // 点击角色按钮弹出层
    async btnRole(id) {
      this.roleLoading = true
      this.showRoleDialog = true
      this.roleList = await getEnabledEmployeeList()
      // 记录当前点击的员工id 方便回显
      this.curUser = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.$nextTick(() => {
        this.roleLoading = false
      })
      // this.roleLoading = false
    },
    // 确认分配角色
    async btnRoleOK() {
      await assignRoles({
        id: this.curUser,
        roleIds: this.roleIds
      })
      this.$message.success('分配用户角色成功')
      this.showRoleDialog = false
    }
  }
}

</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 8px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 40px;
      width: 40px;
      line-height: 40px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}

</style>
